import { _decorator, Component, Node, Input, EventTouch, Vec2,  view} from "cc"
import DataManager from "../Runtime/DataManager"
import EventManager from "../Runtime/EventManager"
import { GAME_MODE_ENUM, PLAYER_ENUM, SOCKET_TYPE } from "../../Enums"
import { sendSocket } from "../service/socket"
import { userStore } from "../service/user"
const { ccclass} = _decorator

@ccclass("JoyAttackManager")
export class JoyAttackManager extends Component {
  input: Vec2 = Vec2.ZERO

  private body: Node
  private defaultPos: Vec2
  private callback
  init() {
    this.body = this.node.getChildByName("Body")
    const { x, y } = this.body.position
    this.defaultPos = new Vec2(x, y)
    this.node.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
    this.node.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
    this.node.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
  }

  onDestroy() {
    this.node.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
    this.node.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    this.node.off(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
  }

  onTouchStart(event: EventTouch) {
    if (DataManager.Instance.drawerNumber != 0) return
    this.unschedule(this.callback)
    let designSize = view.getVisibleSize()
    const touchPos = event.getUILocation()
    this.body.setPosition(touchPos.x - designSize.width / 2 - 150, touchPos.y)
    if (DataManager.Instance.gameMode == GAME_MODE_ENUM.ONLINE) {
      if (userStore()?.info) {
        sendSocket(SOCKET_TYPE.JOYSTICKEAT, {
          name:DataManager.Instance.current_role,
          status: {}
        })
      }
    } else {
      EventManager.Instance.emit("setEatStatus", "");
    }

  }

  onTouchEnd() {
    this.body.setPosition(this.defaultPos.x, this.defaultPos.y, 1)
  }
}
